import * as winston from 'winston'
import * as stackTrace from 'stack-trace'
import * as path from 'path'
import * as fs from 'fs-extra'
import * as DailyRotateFile from 'winston-daily-rotate-file'

const LOGS_PATH: string = path.join(__dirname, '../../logs')
fs.ensureDirSync(LOGS_PATH)

function getFileName(name: string): string {
  return path.join(LOGS_PATH, name)
}

const logger = winston.createLogger({
  level: 'info',
  format: winston.format.json(),
  transports: [
    new winston.transports.File({ filename: getFileName('error.log'), level: 'error' }),
    new DailyRotateFile({
      filename: getFileName('combined-%DATE%.log'),
      datePattern: 'YYYY-MM-DD-HH',
      maxSize: '5m'
    })
  ],
  exceptionHandlers: [
    new winston.transports.File({filename: getFileName('exceptions.log')})
  ]
})

if (JSON.stringify(process.env.NODE_ENV) !== 'production') {
  logger.add(new winston.transports.Console({
    format: winston.format.simple()
  }))
}

const originalErrorLog = logger.error

logger.error = (...args: any[]) => {
  const cellSite = stackTrace.get()[1]
  const extraInfo = args[1] ? args[1] : {}
  return originalErrorLog.apply(logger, [args[0] + '\n', {
    filePath: cellSite.getFileName(),
    lineNumber: cellSite.getLineNumber(),
    ...extraInfo
  }])
}

export default logger